package labuladong.leetcode.editor.cn.leetcode.binarytree;

import labuladong.leetcode.editor.cn._00bean.TreeNode;

import java.util.LinkedList;
import java.util.List;

public class _94_BinaryTreeInorderTraversal {

    //leetcode submit region begin(Prohibit modification and deletion)
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        /* 动态规划思路 */
        // 定义：输入一个节点，返回以该节点为根的二叉树的中序遍历结果
        public List<Integer> inorderTraversal(TreeNode root) {
            LinkedList<Integer> res = new LinkedList<>();
            if (root == null) {
                return res;
            }
            res.addAll(inorderTraversal(root.left));
            res.add(root.val);
            res.addAll(inorderTraversal(root.right));
            return res;
        }

        /* 回溯算法思路 */
        LinkedList<Integer> res = new LinkedList<>();

        // 返回前序遍历结果
        public List<Integer> inorderTraversal2(TreeNode root) {
            traverse(root);
            return res;
        }

        // 二叉树遍历函数
        void traverse(TreeNode root) {
            if (root == null) {
                return;
            }
            traverse(root.left);
            // 中序遍历位置
            res.add(root.val);
            traverse(root.right);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new _94_BinaryTreeInorderTraversal().new Solution();

        TreeNode n3 = new TreeNode(3, null, null);
        TreeNode n2 = new TreeNode(2, n3, null);
        TreeNode n1 = new TreeNode(1, null, n2);

        System.out.println(solution.inorderTraversal(n1));
        System.out.println(solution.inorderTraversal2(n1));
    }
}
